<template>
  <div class="control-panel">
    <!-- 顶部选择区域 -->
    <div class="panel-section top-section">
      <div class="select-container">
        <el-form :model="formData" :inline="true" label-width="120px">
          <el-form-item>
            <el-select
                v-model="formData.agentId"
                placeholder="请选择服务商"
                filterable
                class="select-box"
                size="large"
                style="width: 240px"
            >
              <el-option
                  v-for="item in providerList"
                  :key="item.id"
                  :label="`${item['real_name']} (${item.phone})`"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="bindMerchants">绑定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="panel-section card-list">
      <div class="search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item>
            <!-- 搜索输入框 -->
            <el-input v-model="searchInfo.keyword" placeholder="手机号/名称" style="width: 150px;"/>
          </el-form-item>

          <el-form-item>
            <el-select v-model="searchInfo.on_state" placeholder="请选择状态" style="width: 150px;">
              <el-option v-for="item in statusOptions" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                icon="search"
                @click="onSubmit"
            >查询
            </el-button>
            <el-button
                icon="refresh"
                @click="onReset"
            >重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="300"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="商家名称"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="store_type_name" label="类型"/>
      </el-table>
      <div class="pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100,1000,5000, 10000,]"
            :total="total"
            layout="total, pager, next"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>

</template>

<script setup>
// 引入Vue的响应式API
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {agentSelectList} from "../../apis/agent";
import {storeList} from "../../apis/store";
const providerList = ref([]); // 服务商列表
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const statusOptions = [
  {value: 0, label: '全部'},
  {value: 1, label: '上架'},
  {value: 2, label: '下架'}
]

const tableData = ref([])

// 表单数据
const formData = reactive({
  agentId: '',
  merchants: [],
});
// 搜索条件
const searchInfo = ref({
  keyword: "",
  on_state: 0,
})

const onReset = () => {
  searchInfo.value = {}
}


// 搜索
const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}


// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 处理商家选择
const handleSelectionChange = (selected) => {
  formData.merchants = selected
};

// 绑定商家操作
const bindMerchants = () => {
  // info warning error question
  // OpenMsgDialog("error", '警告', '你好~')
  //     .then((res) => {
  //       console.log("对话框返回:", res);
  //       // 根据返回的结果做进一步处理
  //       if (res === "好") {
  //         console.log("用户点击了'好'按钮");
  //         // 在这里处理用户点击 "好" 后的逻辑
  //       }
  //     })
  //     .catch((error) => {
  //       console.error("对话框调用时发生错误:", error);
  //     });

  if (formData.agentId === '' || formData.agentId === 0) {
    ElMessage.error('请选择服务商')
    return;
  }

  if (formData.merchants.length === 0) {
    ElMessage.error('请选择至少一个商家')
    return;
  }

  const idsArray = formData.merchants.map(item => item.id);


  // ElMessageBox.alert(idsArray, '提醒', {
  //   // if you want to disable its autofocus
  //   // autofocus: false,
  //   confirmButtonText: 'OK',
  //   callback: (action) => {
  //     ElMessage({
  //       type: 'info',
  //       message: `action: ${action}`,
  //     })
  //   },
  // })
  console.log('绑定的服务商ID:', formData.agentId);
  console.log('商家列表:', formData.merchants);


  //
  // // 在这里添加绑定逻辑，如发送请求到后端API
  // console.log('绑定的服务商ID:', formData.provider);
  // console.log('绑定的商家:', formData.selectedMerchants);
  // alert('绑定成功！');
};

// 加载服务商列表
const loadAgentSelect = async () => {
  const res = await agentSelectList()
  if (res.code === 200) {
    providerList.value = res.data.list;
  } else {
    ElMessage.error(res.message)
  }

}

const getTableData = async () => {
  // StoreListReq {page: page.value, page_size: pageSize.value, ...searchInfo.value}
  const res = await storeList({page: page.value, page_size: pageSize.value, ...searchInfo.value})
  console.log(res)

  if (res.code === 200) {
    tableData.value = res.data.data
    total.value = res.data.total_count
    page.value = res.data.page
  } else {
    ElMessage.error(res.message)
  }
}


onMounted(() => {
  getTableData()
  loadAgentSelect()
});
</script>

<style scoped>
.control-panel {
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* 内容过多时滚动 */
}

.panel-section {
  width: 99%;
  margin-bottom: 10px; /* 间距调整 */
  box-sizing: border-box;
}

.top-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
}

.select-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-box {
  @apply p-6 pb-0.5 bg-white rounded mb-3;
}

.pagination {
  @apply flex justify-end;

  .el-pagination__editor {
    .el-input__inner {
      @apply h-8;
    }
  }

  .is-active {
    @apply rounded text-white;
    background: var(--el-color-primary);
    color: #ffffff !important;
  }

  padding-top: 10px;
}
</style>
